package com.example.aslongastoday.ui.backlog;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.aslongastoday.R;
import com.example.aslongastoday.adapter.ViewBackLogGroupAdapter;
import com.example.aslongastoday.bean.BeanFactory;
import com.example.aslongastoday.db.dao.BackLogDao;
import com.example.aslongastoday.db.dao.BackLogGroupDao;
import com.example.aslongastoday.domain.BackLog;
import com.example.aslongastoday.domain.BackLogGroup;
import com.example.aslongastoday.util.TimeUtil;

import java.util.ArrayList;
import java.util.List;

/**
该fragment用于实现一下内容:
 1. 对于待办组(backlog group)的新建和修改(重命名);
 2. 对于待办事件(backlog)的添加
 */
public class EditBacklogFragment extends Fragment implements View.OnTouchListener{

    private TextView tv_title;
    private TextView tv_prompt;
    private EditText et_context;
    private Button btn_commit;
    private String context;
    private Bundle bundle; //来自外部的数据捆
    private Integer backlogGroupId; //所点击的待办项的id
    private FragmentManager fragmentManager; //声明一个管理fragment的fragmentManager

    private FragmentTransaction fragmentTransaction; //声明一个fragmentTransaction
    private BackLogFragment backLogFragment;
    private BackLogGroupDao backLogGroupDao;

    private BackLogDao backLogDao;
    private View rootView; //根视图

    private ViewBackLogGroupAdapter viewBackLogGroupAdapter; //用于处理待办组的视图更新的适配器
    private View topView;

    public EditBacklogFragment() {
        // Required empty public constructor
        this.viewBackLogGroupAdapter = (ViewBackLogGroupAdapter) BeanFactory.getBean("viewBackLogGroupAdapter");
    }

    // 方便更新视图接收参数的构造方法，用该构造方法可以获取上一个fragment的视图适配器
    public EditBacklogFragment(ViewBackLogGroupAdapter viewBackLogGroupAdapter) {
        this.viewBackLogGroupAdapter = viewBackLogGroupAdapter;
    }

    /**
     * 获取上一个fragment传来的视图构造器
     * @return
     */
    public ViewBackLogGroupAdapter getViewBackLogGroupAdapter() {
        return viewBackLogGroupAdapter;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_edit_backlog, container, false);
        //xml标签绑定
        tv_title = rootView.findViewById(R.id.tv_title);
        tv_prompt = rootView.findViewById(R.id.tv_prompt);
        et_context = rootView.findViewById(R.id.et_context);
        //实例化dao类方便数据传输
        backLogGroupDao = new BackLogGroupDao(rootView.getContext());
        backLogDao = new BackLogDao(rootView.getContext());
        fragmentManager  = getActivity().getSupportFragmentManager();;


        //拦截touch请求, 防止泄露
        rootView.setOnTouchListener(this);
        /*
         * 获取从BackLogFragment传来的bundle数据
         * 也可能是获取从ViewBackLogGroupAdapter传来的数据
         */
        bundle = getArguments();
        if(bundle==null){
            //暂留的预防错误的位置
        }
        else{
            String type = bundle.getString("type");
            //界面展示
            switch (type){
                //编辑待办组
                case "edit_backlog_group":
                    tv_title.setText("编辑待办组");
                    tv_prompt.setText("编辑待办组名称: ");
                    et_context.setText(bundle.getString("name"));
                    break;
                //新建待办组
                case "add_backlog_group":
                    tv_title.setText("新建待办组");
                    tv_prompt.setText("新建待办组名称: ");
                    break;
                //新建待办
                case "add_backlog":
                    tv_title.setText("新建待办");
                    tv_prompt.setText("新建待办名称: ");
                    break;
                case "edit_backlog":
                    tv_title.setText("编辑待办");
                    tv_prompt.setText("待办事件: ");
                    et_context.setText(bundle.getString("text"));
                default:
                    break;
            }
            //提交数据到数据库
            //当前的fragment的根视图rootView在onCreateView中已经定义了，无需额外创建
            btn_commit = rootView.findViewById(R.id.btn_commit);
            btn_commit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String type = bundle.getString("type");
                    //界面展示
                    switch (type) {
                        //编辑待办组
                        case "edit_backlog_group":
                            editBackLogGroupName();
                            break;
                        //新建待办组
                        case "add_backlog_group":
                            createNewBackLogGroup();
                            break;
                        //新建待办
                        case "add_backlog":
                            createNewBackLog();
                            break;
                        case "edit_backlog":
                            editBackLog();
                            break;
                        default:
                            break;
                    }
                }
            });
        }
        //返回按钮监听
        onReturnButtonClick();
        return rootView;
    }

    private void editBackLog() {
        context = String.valueOf(et_context.getText());
        int groupId = Integer.parseInt((String) bundle.get("groupId"));
        int id = Integer.parseInt((String) bundle.get("id"));

        BackLog backLog = new BackLog();
        backLog.setContent(context);
        backLogDao.update(groupId,id,backLog);

        setBacklogGroupDataChange();
        Toast.makeText(rootView.getContext(), "修改待办成功~", Toast.LENGTH_SHORT).show();
        fragmentManager = getActivity().getSupportFragmentManager();
        fragmentManager.popBackStack();
    }

    /**
     * 实现编辑修改待办组的名称和提交修改到数据库
     */
    public void editBackLogGroupName(){
        //数据获取并提交新增数据到数据库
        context = String.valueOf(et_context.getText());
        backlogGroupId = bundle.getInt("id");
        BackLogGroup backLogGroup = backLogGroupDao.query(backlogGroupId);
        backLogGroup.setGroupName(context);
        //将修改后的待办组更新到数据库
        backLogGroupDao.update(backLogGroup);
        setBacklogGroupDataChange();
        //给用户的反馈
        Toast.makeText(rootView.getContext(), "修改待办组名称成功~", Toast.LENGTH_SHORT).show();
        //从栈中将当前fragment推出，返回到待办的主fragment
        fragmentManager  = getActivity().getSupportFragmentManager();
        fragmentManager.popBackStack(); //扔出editBacklogFragment
    }

    /**
     * 实现创建一个新的待办组的数据接受和提交到数据库
     */
    public void createNewBackLogGroup(){
        //数据获取并提交新增数据到数据库
        context = String.valueOf(et_context.getText());
        List<BackLog> backLogList = new ArrayList<>();
        BackLogGroup newBackLogGroup = new BackLogGroup(context, TimeUtil.getNowTime(),backLogList);
        //为新加的待办组设置id号
        int id = backLogGroupDao.queryUnfinishedAll().size()+1;
        newBackLogGroup.setId(id);
        List<BackLogGroup> backLogGroupList = new ArrayList<>();
        backLogGroupList.add(newBackLogGroup);
        backLogGroupDao.insert(backLogGroupList);

        //更新数据
        setBacklogGroupDataChange();

        //给用户的反馈
        Toast.makeText(rootView.getContext(), "新建待办组成功~", Toast.LENGTH_SHORT).show();
        //从栈中将当前fragment推出，返回到待办的主fragment
        fragmentManager  = getActivity().getSupportFragmentManager();
        fragmentManager.popBackStack(); //扔出editBacklogFragment
    }

    /**
     * 更新数据视图
     */
    private void setBacklogGroupDataChange(){
        List<BackLogGroup> backLogGroupList = backLogGroupDao.queryUnfinishedAll();
        viewBackLogGroupAdapter.setBackLogGroupList(backLogGroupList);
        viewBackLogGroupAdapter.notifyDataSetChanged();
    }

    /**
     * 实现新建一个待办项的数据接收和提交到数据库
     */
    public void createNewBackLog(){
        // 数据获取并提交新增数据到数据库
        context = String.valueOf(et_context.getText());
        backlogGroupId = bundle.getInt("id");
        // 将数据添加到当前的待办组的待办项列表中1
        BackLog newBackLog = new BackLog();
        newBackLog.setContent(context);
        backLogDao.insert(backlogGroupId,newBackLog);
        setBacklogGroupDataChange();
        //给用户的反馈
        Toast.makeText(rootView.getContext(), "新建待办成功~", Toast.LENGTH_SHORT).show();
        //从栈中将当前fragment推出，返回到待办的主fragment
        fragmentManager  = getActivity().getSupportFragmentManager();
        fragmentManager.popBackStack(); //扔出editBacklogFragment
    }

    /**
     * 实现返回按钮监听
     */
    public void onReturnButtonClick(){
        rootView.findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                //从栈中将当前fragment推出
                fragmentManager  = getActivity().getSupportFragmentManager();
                fragmentManager.popBackStack(); //扔出editBacklogFragment
            }
        });
    }

    // onTouch事件 将上层的触摸事件拦截
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return true;
    }
}